'use strict'
const path = require('path')
const defaultSettings = require('./src/settings.js')
const webpack = require('webpack')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css', 'scss', 'html', 'jpg', 'jpeg', 'png', 'svg']
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title || '驱动程序参数化适配系统' // page title

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
// const port = process.env.port || process.env.npm_config_port || 9528 // dev port
const port = 9551 // dev port
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: './',
  outputDir: process.env.ENV,
  assetsDir: 'static',
  lintOnSave: false,
  productionSourceMap: false,
  devServer: {
    host: '0.0.0.0',
    port: port,
    open: true,
    proxy: {
      '/api/': {
        // 分析中心
        target: 'http://8.134.156.156:8073/', // 对应自己的接口
        // target: 'http://10.29.4.230:8073/', // yz地址
        // target: 'http://10.29.4.243:8072/', // xhp地址
        // target: 'http://10.29.4.232:8072/', // nz地址
        // target: 'http://10.29.4.229:8073/', // kh地址
        // target: 'http://10.29.4.239:8073/', // wy地址
        // target: 'http://10.29.4.238:8073', // lq地址
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/api': '' // 通过pathRewrite重写地址，将前缀/api转为/
        }
      },
      '/api-prod/': {
        target: 'http://localhost:8080/', // 测试环境
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/api-prod': '/' // 通过pathRewrite重写地址，将前缀/api转为/
        }
      }
    },
    overlay: {
      warnings: false,
      errors: true
    }
    // before: require('./mock/mock-server.js')
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    externals: {},
    // performance: {
    //   // 警告 webpack 的性能提示
    //   hints: 'warning',
    //   // 入口起点的最大体积
    //   maxEntrypointSize: 50000000,
    //   // 生成文件的最大体积
    //   maxAssetSize: 30000000,
    //   // 只给出 js 文件的性能提示
    //   assetFilter: function (assetFilename) {
    //     return assetFilename.endsWith('.js')
    //   }
    // },
    plugins: [
      new CompressionWebpackPlugin({
        algorithm: 'gzip',
        test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
        threshold: 10240, // 对超过10kb的数据进行压缩
        minRatio: 0.8
      }),
      new webpack.optimize.LimitChunkCountPlugin({
        maxChunks: 5,
        minChunkSize: 100
      }),
      new webpack.ProvidePlugin({
        $: 'jquery',

        jQuery: 'jquery',

        'windows.jQuery': 'jquery'
      })
      // new BundleAnalyzerPlugin()
    ]
  },
  css: {
    loaderOptions: {
      scss: {
        // 引入自定义主题文件
        prependData: `@import "@/styles/element-variables.scss";`
      }
    }
  },
  chainWebpack(config) {
    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugins.delete('preload')

    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch')

    // set svg-sprite-loader
    config.module.rule('svg').exclude.add(resolve('src/assets/svg')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/svg'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap((options) => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    config.when(process.env.NODE_ENV !== 'development', (config) => {
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/
          }
        ])
        .end()
      config.optimization.splitChunks({
        chunks: 'all',
        maxInitialRequests: Infinity, // 最大并行请求数，为了以防万一，设置无穷大即可
        minSize: 20000, // 引入的模块大于20kb才做代码分割，官方默认20000，这里不用修改了
        maxSize: 60000, // 若引入的模块大于60kb，则告诉webpack尝试再进行拆分
        cacheGroups: {
          // libs: {
          //   name: 'chunk-libs',
          //   test: /[\\/]node_modules[\\/]/,
          //   priority: 10,
          //   chunks: 'initial' // only package third parties that are initially dependent
          // },
          // elementUI: {
          //   name: 'chunk-elementUI', // split elementUI into a single package
          //   priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
          //   test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
          // },
          vendors: {
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
            // chunks: 'all',
            name(module) {
              // 设定分包以后的文件模块名字，按照包名字替换拼接一下
              const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
              return `npm.${packageName.replace('@', '')}`
            }
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      })
      config.optimization.runtimeChunk('single')
      config.optimization.minimizer('terser').tap((options) => {
        options[0].terserOptions.compress.drop_console = true
        return options
      })
    })
  }
}
